package com.yuwj.chinaa.util;

import android.app.Activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * activity收集类,用于在关闭应用时,finish所有的activity
 * 把对activity的强引用变为弱引用,防止内存泄露.
 */

public class ActivityCollectUtil {
    private static ActivityCollectUtil activityCollectUtil = new ActivityCollectUtil();
    private List<WeakReference<Activity>> activities;
    private WeakReference<Activity> topActivity;

    private ActivityCollectUtil() {
        activities = new ArrayList<>();
    }

    public static ActivityCollectUtil getInstance() {
        return activityCollectUtil;
    }

    public void addActivity(Activity activity) {
        WeakReference<Activity> act = new WeakReference<>(activity);
        activities.add(act);
    }

    public void removeActivity(Activity activity) {
        activities.remove(activity);
    }

    public Activity getTopActivity() {
        if (topActivity != null) {
            return topActivity.get();
        }
        return null;
    }

    public void setTopActivity(Activity activity) {
        if (activity != null) {
            WeakReference<Activity> p = new WeakReference<Activity>(activity);
            topActivity = p;
        } else {
            topActivity = null;
        }
    }

    public void finishAll() {

        for (WeakReference<Activity> activity : activities) {
            Activity act = activity.get();
            if (act != null && !act.isFinishing()) {
                act.finish();
            }
        }
    }
}
